<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {
  reqAddOrUpdateRole,
  reqDelRole,
  reqGetAllPermission,
  reqGetAllRole,
  reqSetPermission
} from "@/api/acl/role/index.ts";
import type {ResRoleType, Role} from "@/api/acl/role/type.ts";
import {ElMessage} from "element-plus";
import type {MenuData} from "@/api/acl/user/type.ts";

let currentPage = ref<number>(1);
let pageSize = ref<number>(4);
let total = ref<number>(20);
let roleName = ref<string>("");
let roleList = ref<Role[]>([]);

const getRoles = async () => {
  let result: ResRoleType = await reqGetAllRole(currentPage.value, pageSize.value, roleName.value);
  if (result.data.code === 200) {
    roleList.value = result.data.data.records;
    total.value = result.data.data.total;
  }
}
const handleCurrentChange = () => {
  getRoles();
}
const handleSizeChange = () => {
  getRoles();
}
const search = () => {
  getRoles();
}
onMounted(() => {
  getRoles();
})

let dialogVisible = ref<boolean>(false);
let roleParam = reactive<Role>({roleName: ""});
const toAdd = () => {
  Object.assign(roleParam, {roleName: "", id: ""});
  dialogVisible.value = true;
}
const toUpdate = (row: Role) => {
  Object.assign(roleParam, row);
  dialogVisible.value = true;
}
const confirm = async () => {
  let result = await reqAddOrUpdateRole(roleParam);
  console.log(result);
  if (result.data.code === 200) {
    ElMessage({
      type: "success",
      message: roleParam.id ? "编辑成功" : "成功成功"
    })
    await getRoles();
    dialogVisible.value = false;
  } else
    ElMessage({
      type: "error",
      message: roleParam.id ? "编辑失败" : "成功失败"
    })
}
// 权限分配
let drawVisible = ref<boolean>(false);
let menuList = ref<MenuData[]>([]);
let selectedMenu = ref<number[]>([]);
let defaultProps = {
  children: 'children',
  label: 'name'
};
const tree = ref();
const assignPermission = async (id: number) => {
  roleParam.id = id;
  selectedMenu.value = [];
  let result = await reqGetAllPermission(id);
  if (result.data.code === 200) {
    menuList.value = result.data.data;
    selectedMenu.value = filterMenu(menuList.value, selectedMenu.value);
  }
  drawVisible.value = true;
}

const filterMenu = (all: MenuData[], selected: number[]) => {
  all.forEach((item) => {
    if ((!item.children || 0 == item.children.length) && item.select)
      selected.push(item.id);
    if (item.children && item.children.length > 0)
      filterMenu(item.children, selected);
  });
  return selected;
}
const setPermission = async () => {
  const roleId = roleParam.id;
  let selectID = tree.value.getCheckedKeys();
  let halfSelect = tree.value.getHalfCheckedKeys();
  const permissionId = selectID.concat(halfSelect);
  let result = await reqSetPermission(roleId as number,permissionId);
  if (result.data.code === 200) {
    ElMessage.success('分配成功');
    drawVisible.value = false;
  }
}
const removeRole = async (id:number) => {
  let result = await reqDelRole(id);
  if (result.data.code === 200) {
    ElMessage.success("删除成功");
    await getRoles();
  }
}
</script>

<template>
  <div>
    <el-card style="height: 80px;margin: 20px 0">
      <el-form inline class="search_form">
        <el-form-item label="名称">
          <el-input v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!roleName" @click="search">搜索</el-button>
          <el-button type="info">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-button type="primary" icon="Plus" @click="toAdd">添加职位</el-button>
      <el-table border style="margin: 10px 0;" :data="roleList">
        <el-table-column label="#" type="index" align="center"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" width="260px">
          <template #default="{row}">
            <el-button type="primary" icon="User" title="分配权限" size="small"
                       @click="assignPermission(row.id)"></el-button>
            <el-button type="warning" icon="Edit" title="编辑" size="small" @click="toUpdate(row)"></el-button>
            <el-button type="danger" icon="Delete" title="删除" size="small" @click="removeRole(row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[4, 6, 8, 10]"
          layout="prev, pager, next, jumper, ->, sizes, total,"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog width="35%" v-model="dialogVisible" :title="roleParam.id?'编辑角色':'添加角色'">
      <el-form label-width="80px" label-position="right">
        <el-form-item label="角色名">
          <el-input v-model="roleParam.roleName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button type="info" @click="dialogVisible=false">取消</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawVisible">
      <template #header>
        分配权限
      </template>
      <template #default>
        <el-tree
            ref="tree"
            :data="menuList"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="selectedMenu"
            :props="defaultProps"
        />
      </template>
      <template #footer>
        <el-button type="primary" @click="setPermission">确定</el-button>
        <el-button type="info" @click="drawVisible=false">取消</el-button>
      </template>
    </el-drawer>
  </div>


</template>

<style scoped lang="scss">
.search_form {
  display: flex;
  justify-content: space-between;
}
</style>